'''
Case Type： 故障&可靠性测试
Case Name： 主节点故障	sql间并行执行过程中dn主故障
Create At: 2020/07/02
@zou_jialiang0505328114
Descption:
步骤 1.启动数据库
步骤 2.开始执行dml操作
步骤 3.执行dml期间杀掉备进程
步骤 4.查询数据库状态
步骤 5.重新拉起数据库并检查状态
'''
import time
import unittest
import _thread
from yat.test import Node
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import *


class Deletaduit(unittest.TestCase):
    sh_primy = CommonSH('PrimaryDbUser')
    sh_standby = CommonSH('Standby1DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case003.py start------------')
        self.primary_dbuser = Node(node='PrimaryDbUser')
        self.primary_root = Node(node='PrimaryRoot')
        self.standby1_root = Node(node='Standby1Root')
        self.standby1_dbuser = Node(node='Standby1DbUser')
        self.com = Common()
        self.t_name1 = 't_test1'
        self.t_name2 = 't_test2'

    def test_startdb(self):
        # 建表
        self.log.info('----------------------------创建表，并写入数据-----------------------------')

        sql = f'''
                drop table if exists {self.t_name1};
                create table {self.t_name1}(t_id integer, t_desc character(20));

                drop table if exists {self.t_name2};
                create table {self.t_name2}(t_id integer, t_desc character(20));
                '''
        self.log.info(sql)
        msg = self.sh_primy.executDbSql(sql)
        self.log.info(msg)

        insert_sql1 = f"insert into {self.t_name1} values (1,'aaa');"
        insert_sql2 = f"insert into {self.t_name2} values (1,'bbb');"
        self.log.info('开始执行dml操作')
        _thread.start_new_thread(self.sh_primy.cycle_exec_sql, (insert_sql1, 10000,))
        _thread.start_new_thread(self.sh_primy.cycle_exec_sql, (insert_sql2, 10000,))

        time.sleep(5)

        self.log.info('执行dml期间杀掉备进程')
        msg = self.com.kill_pid(self.standby1_root, 9)
        self.assertEqual(msg, '')

        self.log.info('查看数据库状态')
        status = self.sh_primy.getDbClusterStatus("status")
        self.assertFalse(status)
        self.log.info(status)

        self.log.info('重新拉起数据库并检查状态')
        result = self.sh_primy.startDbCluster()
        self.assertTrue(result)

        time.sleep(3)

        status = self.sh_primy.getDbClusterStatus("status")
        self.log.info(status)
        self.assertTrue(status)

    def tearDown(self):
        self.log.info("---------------------this is tearDown-------------------------")
        sql = f'''drop table if exists {self.t_name1};drop table if exists {self.t_name2};'''
        self.log.info(sql)
        msg = self.sh_primy.executDbSql(sql)
        self.log.info(msg)
